<template>
  <el-dialog
    title="分配权限"
    :visible="visible"
    @close="closeDialog"
    @open="openDialog">
    <!-- data：树形数据 -->
    <!-- props：修改数据中的 key -->
    <!-- default-expand-all：默认展开全部节点 -->
    <!-- show-checkbox：显示选择框 -->
    <!-- check-strictly：关闭父子关联 -->
    <!-- node-key：为每个树节点设置一个 key 值，这样我们可以拿到所有选中的节点 id -->
    <el-tree
      ref="treeRef"
      :data="list"
      :props="{ label: 'name' }"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { recurTransTree } from '@/utils/transTree'
import { assignPermission, getRoleDetail } from '@/api/setting'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  methods: {
    // 关闭弹窗
    closeDialog() {
      this.$emit('close-assign-permission')
    },
    // 获取权限点列表数据
    async fetchPermissionList() {
      const res = await getPermissionList()
      this.list = recurTransTree(res.data, '0')
      // 获取角色详细信息数据
      const roleDetail = await getRoleDetail(this.roleId)
      this.$refs.treeRef.setCheckedKeys(roleDetail.data.permIds)
    },
    // 弹窗打开
    openDialog() {
      this.fetchPermissionList()
    },
    // 给角色分配权限
    async submit() {
      await assignPermission({
        id: this.roleId, // 角色id
        permIds: this.$refs.treeRef.getCheckedKeys() // 给角色分配的权限id组成的数组
      })
      // 提示用户
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.closeDialog()
    }
  }
}
</script>

<style>

</style>